#include "MenuButton.h"
#include "stdio.h"
#include "d3dapplication.h"
#include "SoundManager.h"
#include "FuriousTourist.h"

MenuButton::MenuButton(void)
{
	
}

MenuButton::~MenuButton(void)
{
	// release the textures
	mTextureLit->Release();
	mTextureUnlit->Release();
}

MenuButton::MenuButton(UINT id, float xFrac, float yFrac, float bbWidth, float bbHeight, int h, int w, LPCSTR texLit, LPCSTR texUnlit, LPCSTR text, ID3DXSprite* sprite, ID3DXFont* font, HWND wnd)
{
	mPlaySound = true;

	idNum = id;
	
	xf = xFrac;
	yf = yFrac;

	screenX = xf * bbWidth;
	screenY = yf * bbHeight;

	mCenter = D3DXVECTOR3((float)w/2, (float)h/2, 0.0f);
	mFont = font;
	mSprite = sprite;
	mText = new char[256];
	strcpy((char*)mText, text);
	
	// create the textures
	D3DXCreateTextureFromFileEx(gD3DDevice, texLit, w, h, 1, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 255), 0, NULL, &mTextureLit);
	D3DXCreateTextureFromFileEx(gD3DDevice, texUnlit, w, h, 1, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 255), 0, NULL, &mTextureUnlit);

	mWnd = wnd;

	mIsPressed = false;
}

bool MenuButton::isMouseOver()
{
	POINT p;

	// simple function to get cursor coordinates
	// DirectInput is a PITA...
	GetCursorPos(&p);

	ScreenToClient(mWnd, &p);

	float x1 = screenX - mCenter.x;
	float y1 = screenY - mCenter.y;
	float x2 = screenX + mCenter.x;
	float y2 = screenY + mCenter.y;

	if (p.x > x1 &&
		p.x < x2 &&
		p.y > y1 &&
		p.y < y2 )
	{
		// if the cursor is over it, play a sound effect
		if (mPlaySound)
		{
			SOUNDMANAGER->SoundPlay(SOUND_MENUCLICK2);
			mPlaySound = false;
		}

		return true;
	}
	else
	{
		// if they take the cursor away, allow the sound to be triggered again
		mPlaySound = true;
		return false;
	}	
}

void MenuButton::Render()
{
	// renders the button based on the current state and displays text (format
	// given by the passed text object.
	// assumes the D3D rendering process has already begun

	D3DXVECTOR3 pos;
	pos.x = screenX;
	pos.y = screenY;
	pos.z = 0.0f;

	if (mIsPressed)
		mSprite->Draw(mTextureLit, 0, &mCenter, &pos, D3DCOLOR_ARGB(255, 255, 255, 255));
	else
		mSprite->Draw(mTextureUnlit, 0, &mCenter, &pos, D3DCOLOR_ARGB(255, 255, 255, 255));

	RECT R;

	R.bottom	= screenY + mCenter.y;
	R.left		= screenX - mCenter.x;
	R.right		= screenX + mCenter.x;
	R.top		= screenY - mCenter.y;

	mFont->DrawTextA(mSprite, mText, -1, &R, DT_NOCLIP | DT_CENTER | DT_VCENTER, D3DCOLOR_ARGB(255, 0, 0, 0));

}

void MenuButton::UpdateSize(float bbWidth, float bbHeight)
{
	screenX = xf * bbWidth;
	screenY = yf * bbHeight;
}